let { pages, view, sortBy, groupBy, css, options } = input;

// Error Handling
if (!pages && pages != "") { dv.span('> [!ERROR] Missing pages parameter\n> \n> Please set the pages parameter like\n> \n> `pages: ""`'); return false };
if (!view) { dv.span('> [!ERROR] Missing view parameter\n> \n> Please set a default view inside view parameter like\n> \n> `view: "table"`'); return false };

// Get, Set, Eval Pages
if (pages == "") {
    var items = dv.pages();
} else {
    if (pages.startsWith("dv.pages")) {
        var items = eval(pages);
    } else {
        // 处理路径，确保正确处理特殊字符
        try {
            // 如果路径包含特殊字符，使用引号包裹
            if (pages.match(/[^a-zA-Z0-9\/\-_\.]/)) {
                pages = `"${pages}"`;
            }
            // 移除开头的斜杠
            if (pages.startsWith("/")) {
                pages = pages.substring(1);
            }
            if (pages.startsWith('"/"')) {
                pages = '"' + pages.substring(3);
            }
            var items = dv.pages(pages);
        } catch (error) {
            dv.span('> [!ERROR] Invalid path format\n> \n> Error: ' + error.message);
            return false;
        }
    }
};

// 如果没有找到任何页面，显示提示信息
if (!items || items.length === 0) {
    dv.span('> [!NOTE] No pages found in the specified path');
    return false;
}

// Variables
var tid = (new Date()).getTime();
const rootNode = dv.el("div", "", { cls: "notionView " + options, attr: { id: "notionView" + tid, view: view, style: 'position:relative;-webkit-user-select:none!important' } });
if (css) { var style = document.createElement("style"); style.innerHTML = css; rootNode.append(style) };

// Icons
var tableIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3h18v18H3zM3 9h18M3 15h18M9 9v12M15 9v12"/></svg>';
var boardIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M9 9v12M15 9v12"/></svg>';
var galleryIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>';
var filterIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"></polygon></svg>';
var sortIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 5h10M11 9h7M11 13h4M3 17h18M3 5l4 4M7 5l-4 4"/></svg>';

// Initialize
setButtons();
setFilterPopUp();
setSortPopUp();
eval("get" + capitalize(view))(items);

function capitalize(str) {
    return str[0].toUpperCase() + str.slice(1);
}

function setButtons() {
    var buttons = "<button class='filter'>" + filterIcon + "</button><button class='sort'>" + sortIcon + "</button><button class='tableView' title='Table'>" + tableIcon + "</button><button class='boardView' title='Board'>" + boardIcon + "</button><button class='galleryView' title='Gallery'>" + galleryIcon + "</button>";
    rootNode.querySelector("span").appendChild(dv.el("div", buttons, { cls: "buttons", attr: {} }));
    setButtonEvents();
}

function setButtonEvents() {
    rootNode.querySelectorAll('button').forEach(btn => btn.addEventListener('click', (() => {
        var activeView = rootNode.getAttribute("view");
        if (btn.className == "filter") {
            rootNode.querySelector('.filterPopup').classList.toggle("active");
        } else if (btn.className == "sort") {
            rootNode.querySelector('.sortPopup').classList.toggle("active");
        } else if (btn.className == "tableView") {
            getTable(items);
        } else if (btn.className == "boardView") {
            getBoard(items);
        } else if (btn.className == "galleryView") {
            getGallery(items);
        }
        btn.blur();
    })));
}

function setFilterPopUp() {
    var filterContent = "<div class='filterHeader'>Filter</div><div class='filterContent'></div>";
    rootNode.querySelector("span").appendChild(dv.el("div", filterContent, { cls: "filterPopup" }));
}

function setSortPopUp() {
    var sortContent = "<div class='sortHeader'>Sort</div><div class='sortContent'></div>";
    rootNode.querySelector("span").appendChild(dv.el("div", sortContent, { cls: "sortPopup" }));
}

function getProperties(items) {
    let properties = new Set();
    items.forEach(item => {
        Object.keys(item).forEach(key => {
            if (key !== "file") {
                properties.add(key);
            }
        });
    });
    return Array.from(properties);
}

// 修改文件路径处理函数
function getRelativePath(absolutePath) {
    // 如果是绝对路径，转换为相对路径
    if (absolutePath.startsWith("/")) {
        return absolutePath.substring(1);
    }
    return absolutePath;
}

function getTable(items) {
    removeExistingView();
    rootNode.setAttribute("view", "table");

    let properties = getProperties(items);
    let tableContent = "<table><thead><tr>";

    // Add headers
    tableContent += "<th>Title</th>";
    properties.forEach(prop => {
        tableContent += `<th>${prop}</th>`;
    });
    tableContent += "</tr></thead><tbody>";

    // Add rows
    items.forEach(item => {
        const relativePath = getRelativePath(item.file.path);
        tableContent += `<tr><td><a class='internal-link' href='${relativePath}'>${item.file.name}</a></td>`;
        properties.forEach(prop => {
            let value = item[prop] || "";
            if (Array.isArray(value)) {
                value = value.join(", ");
            }
            tableContent += `<td>${value}</td>`;
        });
        tableContent += "</tr>";
    });

    tableContent += "</tbody></table>";
    rootNode.querySelector("span").appendChild(dv.el("div", tableContent, { cls: "tableView" }));
}

function getBoard(items) {
    removeExistingView();
    rootNode.setAttribute("view", "board");

    if (!groupBy) {
        groupBy = getProperties(items)[0];
    }

    let groups = {};
    items.forEach(item => {
        let groupValue = item[groupBy] || "No " + groupBy;
        if (!groups[groupValue]) {
            groups[groupValue] = [];
        }
        groups[groupValue].push(item);
    });

    let boardContent = "<div class='boardColumns'>";
    Object.keys(groups).forEach(group => {
        boardContent += `<div class='boardColumn'><div class='columnHeader'>${group}</div><div class='columnContent'>`;
        groups[group].forEach(item => {
            const relativePath = getRelativePath(item.file.path);
            boardContent += `<div class='card'><a class='internal-link' href='${relativePath}'>${item.file.name}</a></div>`;
        });
        boardContent += "</div></div>";
    });
    boardContent += "</div>";

    rootNode.querySelector("span").appendChild(dv.el("div", boardContent, { cls: "boardView" }));
}

function getGallery(items) {
    removeExistingView();
    rootNode.setAttribute("view", "gallery");

    let galleryContent = "<div class='galleryGrid'>";
    items.forEach(item => {
        let properties = getProperties([item]);
        const relativePath = getRelativePath(item.file.path);
        let cardContent = `<div class='card'><div class='cardHeader'><a class='internal-link' href='${relativePath}'>${item.file.name}</a></div><div class='cardContent'>`;
        properties.forEach(prop => {
            let value = item[prop] || "";
            if (Array.isArray(value)) {
                value = value.join(", ");
            }
            cardContent += `<div class='property'><span class='propertyName'>${prop}:</span> ${value}</div>`;
        });
        cardContent += "</div></div>";
        galleryContent += cardContent;
    });
    galleryContent += "</div>";

    rootNode.querySelector("span").appendChild(dv.el("div", galleryContent, { cls: "galleryView" }));
}

function removeExistingView() {
    const views = ['.tableView', '.boardView', '.galleryView'];
    views.forEach(view => {
        const element = rootNode.querySelector(view);
        if (element) {
            element.remove();
        }
    });
} 